package cn.chiship.framework.upms.biz.base.service.impl;

import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.framework.upms.biz.system.entity.UpmsRegion;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.core.base.constants.CacheConstants;
import cn.chiship.sdk.framework.pojo.vo.RegionVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lijian
 */
@Component
public class CacheAsyncService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CacheAsyncService.class);

    @Resource
    RedisService redisService;
    @Async("asyncServiceExecutor")
    public void cacheRegionsCity(Long id, List<UpmsRegion> regions) {
        String key = CommonCacheConstants.buildKey(CacheConstants.REDIS_REGIONS_PREFIX);

        LOGGER.info("-------------------------cacheRegionsCity start-----------------------------------------");

        /**
         * 市
         */
        List<RegionVo> cityVos = new ArrayList<>();
        for (UpmsRegion region : regions) {
            if (id.equals(region.getPid())) {
                cityVos.add(copy(region));
            }
        }
        redisService.hset(key, String.valueOf(id), cityVos);


        /**
         * 县 district
         */
        List<RegionVo> tempDistrictVos = new ArrayList<>();
        for (RegionVo city : cityVos) {
            List<RegionVo> districtVos = new ArrayList<>();
            for (UpmsRegion region : regions) {
                if (region.getPid().equals(city.getId())) {
                    districtVos.add(copy(region));
                }
            }
            tempDistrictVos.addAll(districtVos);
            redisService.hset(key, String.valueOf(city.getId()), districtVos);
        }

        /**
         * 街道 street
         */
        for (RegionVo district : tempDistrictVos) {
            List<RegionVo> streetVos = new ArrayList<>();
            for (UpmsRegion region : regions) {
                if (region.getPid().equals(district.getId())) {
                    streetVos.add(copy(region));
                }
            }
            redisService.hset(key, String.valueOf(district.getId()), streetVos);
        }


        LOGGER.info("-------------------------cacheRegionsCity end----------------------------------------");


    }


    public RegionVo copy(UpmsRegion upmsRegion) {
        RegionVo regionVo = new RegionVo();
        BeanUtils.copyProperties(upmsRegion, regionVo);
        return regionVo;
    }

}
